﻿using ErrorOr;
using Gym.Application.Common.Interfaces;
using Gym.Domain.SessionAggregate;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gym.Application.Sessions.Queries.GetSession
{
    public class GetSessionQueryHandler : IRequestHandler<GetSessionQuery, ErrorOr<Session>>
    {
        private readonly IRoomsRepository _roomRepository;
        private readonly ISessionsRepository _sessionRepository;

        public GetSessionQueryHandler(IRoomsRepository roomRepository, ISessionsRepository sessionRepository)
        {
            _roomRepository = roomRepository;
            _sessionRepository = sessionRepository;
        }

        public async Task<ErrorOr<Session>> Handle(GetSessionQuery request, CancellationToken cancellationToken)
        {
            var room = await _roomRepository.GetByIdAsync(request.RoomId);
            if (room is null)
            {
                return Error.NotFound(description: "没有找到该教室信息");
            }

            if (!room.HasSession(request.SessionId))
            {
                return Error.NotFound(description: "没有找到该课程信息");
            }

            if (await _sessionRepository.GetByIdAsync(request.SessionId) is not Session session)
            {
                return Error.NotFound(description: "没有找到该课程信息");
            }

            return session;
        }
    }
}
